# -*- encoding: utf-8 -*-
'''
@File    :   auto_back.py
@Author  :   Loopher 
@Version :   1.0
@License :   (C)Copyright 2020-2021, Loopher
@Desc    :   None
'''

# Here put the import lib
import sys
import json
from paramiko import SSHClient,AutoAddPolicy
from scp import SCPClient
import os
import codecs
import time

path_name ="config.json"
MAX_LOG_SIZE= 1024*1024* 2#保存的最大日志 2MB  @

def record_log(pwd,info):
    """
    记录一下程序运行的时间便于查看是否可以执行
    """
    log_file = pwd+"backup.log"
    if os.path.getsize(log_file) > MAX_LOG_SIZE:
        os.remove(log_file) #直接删掉这个文件即可
    with codecs.open(log_file,"a+",encoding="utf-8") as fp:
        fp.write(info)
        fp.write("\n")

def load_config(pwd):
    path = pwd+path_name
    assert os.path.isfile(path)
    with codecs.open(path,"r",encoding="utf-8") as fp:
        return json.load(fp)

def scp_file(user,host,password,dst,remote_root,current_file_fmt):

    with SSHClient() as ssh:
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        ssh.connect(
            hostname=host,
            port="22",
            username=user,
            password=password
        )
        # 读取当前文件的名称
        _,out,_ = ssh.exec_command(f"ls -l {remote_root}")
        # go = False
        f= None
        fs = []
        for l in out:
            # fs.append(l)
            # print(l)
            n = l.split(" ")[-1].strip()
            if current_file_fmt in n:
                f = n
                break
            # print(" -> ",l , " name: ",n)
            # if l.contains(current_file_fmt):
            #     f = l 
            #     break
        # print("===========>> ",f)
        if f is None:
            print("-> 没有找到备份文件")
            return 
        src =remote_root+f

        with SCPClient(ssh.get_transport()) as scp:
            print("--> ",src)
            print("==> ",dst)
            scp.get(src,dst)
            if os.path.isfile(dst):
                print("-> 文件下载成功")

def down_load_backup(pwd):

    """
    pwd : 传入的当前程序运行路径，默认是格式D:\pythonCode\
        有一个路径符号，用于记录备份日志和读取配置文件，默认配置文件在程序运行的路径下
    """
    configs = load_config(pwd)
    msgs = []
    for config in configs['servers']:
        ssh_ip = config['ssh_ip']
        # 创建当前的备份路径,备份路径是从confi.json中配置
        #
        backup_root =config['local_backup_path'] +os.sep+ssh_ip
        if not os.path.isdir(backup_root):
            os.makedirs(backup_root)

        ssh_port = config['ssh_port']
        username = config['username']
        password = config['password']
        current_file_fmt =config['db_name'] +"_"+ time.strftime("%Y%m%d",time.localtime())
        sql_file = current_file_fmt+config['backup_suffix']
        # remote_backup_file = config['backup_root']+sql_file
        local_backup_file = backup_root+os.sep+sql_file
        if os.path.isfile(local_backup_file):
            # print()
            msgs.append("服务器备份 ip: "+config['ssh_ip']+" 本地已经存在，不需要更新 备份路径："+local_backup_file)
            continue 
        
        print("**"*40)
        print(f"备份服务器数据server ip : {ssh_ip}")
        print(f"开始备份数据 {sql_file}")
        # print(f"{remote_backup_file}")
        print(f"username = {username} password = {password} ")
        print(f"ssh_ip =  {ssh_ip} ssh_port = {ssh_port}")
        print("**"*40)
        # print("--> remote root: ",os.path.dirname(remote_backup_file))
        print("curret_file_fmt: ",current_file_fmt)

        msg = f"备份服务器数据server ip : {ssh_ip} "

        try:
            scp_file(username,ssh_ip,password,local_backup_file,config['backup_root'],current_file_fmt)
            msg += "\n备份成功 保存路径："+local_backup_file
        except Exception as e:
            msg  = msg+"\n执行程序失败，error: {}".format(e)
        msg += "\n运行时间: "+time.strftime("%Y/%m/%d %H:%M:%S",time.localtime())
    for m in msgs:
        record_log(pwd,m)

        

if __name__=="__main__":

    down_load_backup(sys.argv[1])# 传入路径，默认给定当前的路径